package com.vcredit.creditcat.service.speedloan;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vcredit.creditcat.dto.creditrepository.ItemStatusDto;
import com.vcredit.creditcat.dto.product.ProductApplyResultDto;
import com.vcredit.creditcat.dto.speedloan.SpeedloanPrecheckItemDto;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.CustProductApply;
import com.vcredit.creditcat.model.CustSupplementItem;
import com.vcredit.creditcat.model.ProcessSpecial;
import com.vcredit.creditcat.model.ProcessSpecialCust;
import com.vcredit.creditcat.service.CustProductApplyService;
import com.vcredit.creditcat.service.CustService;
import com.vcredit.creditcat.service.product.CreditProductService;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.vcredit.framework.util.JacksonUtil;

@Service
public class SpeedloanTaskService {

	@Autowired
	private CustService custService;
	@Autowired
	private ProcessSpecialService processSpecialService;
	@Autowired
	private SpeedloanService speedloanService;
	@Autowired
	private CreditProductService creditProductService;
	@Autowired
	private ProcessSpecialCustService processCustService;
	@Autowired
	private CustProductApplyService custProductApplyService;
	
	/**
	 * 处理用户快速贷款流程记录
	 * @author zhaoqi01
	 * @param processSpecialCust
	 * @throws Exception
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public void handleSpeedloan(ProcessSpecialCust processSpecialCust) throws Exception {
		Cust cust = custService.findById(processSpecialCust.getCustId());
		Long productId = null;
		List<ProcessSpecial> processSpecials = processSpecialService.findAll();
		for (ProcessSpecial processSpecial : processSpecials) {
			if(processSpecial.getSpecialId().longValue() == processSpecialCust.getSpecialId().longValue()){
				productId = processSpecial.getProductId();
				break;
			}
		}
		Map<String, Object> precheckResult = speedloanService.precheck(productId, cust, false);
		int status = (int)precheckResult.get("status");
		SpeedloanPrecheckItemDto precheckItemDto = (SpeedloanPrecheckItemDto) precheckResult.get("precheckItemDto");
		int creditPhase = precheckItemDto.getCreditPhase();
		// 在预检中已经处理过了status为0或3的情况，这里只需要处理status为1的情况，status为2不处理
		if(status == 1 && (creditPhase == 2 || creditPhase == 5)) {// 认证项全部通过，并且授信状态为审批中或者有可申请的产品
			Object object = precheckResult.get("applyProduct");
			CustProductApply custProductApply = object == null ? null : (CustProductApply)object;
			if(null != custProductApply && custProductApply.getAuditResult() == 2) {
				// 如果该产品已经在审批中了，需要修改申请流程状态
				processSpecialCust.setStatus(2);
				processCustService.update(processSpecialCust);
				return;
			}
			
			// 认证项全部通过，申请产品
			Map<String,Object> otherParams = JacksonUtil.Json2Map(processSpecialCust.getCustParam());
			List<ItemStatusDto> itemStatusDtos = (List<ItemStatusDto>)precheckResult.get("itemStatusDtos");
			List<CustSupplementItem> custSupplementItems = (List<CustSupplementItem>)precheckResult.get("custSupplementItems");
			ProductApplyResultDto applyResult = creditProductService.apply(cust, productId, otherParams,custSupplementItems,itemStatusDtos);
			if(applyResult.getCheckState() == 2) {
				// 存在失效认证项，在申请时候已经重置认证项状态，所以现在的状态为缺失
				processSpecialCust.setStatus(0);
				processCustService.update(processSpecialCust);
			} else {
				// 产品申请正常提交后，流程状态置为已提交
				processSpecialCust.setStatus(2);
				processCustService.update(processSpecialCust);
			}
			
			// 正常情况下走到这一步有两种情况：1、认证项没通过（缺失或失效） 2、正常提交申请； 产品申请记录为null或者授信状态为0、1、2、22
			// 如果此时的授信状态为22（快贷流程提交中），无论是第一种情况还是第二种情况，都需要将授信状态设置为0（失败）
			CustProductApply findNewApplyProduct = custProductApplyService.findNewApplyProduct(productId, cust.getCustId());
			if(findNewApplyProduct != null && findNewApplyProduct.getAuditResult() == 22) {
				findNewApplyProduct.setAuditResult(0);
				findNewApplyProduct.setIsApply(true);
				findNewApplyProduct.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(new Date()));
				findNewApplyProduct.setRejectMsg(CustProductApplyService.AUTH_ITEM_UNDONE_MSG);
				custProductApplyService.update(findNewApplyProduct);
			}
		}
	}
}
